package com.battle.service.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.Organization;
import com.battle.pojo.enums.OrganizationTypeEnum;
import com.battle.pojo.param.organization.*;
import com.battle.pojo.vo.organization.*;
import com.battle.pojo.dto.organization.*;
import com.battle.service.repository.in.OrganizationRepository;
import com.battle.service.service.in.OrganizationService;
import com.battle.service.utils.ExcelUtils;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.battle.pojo.excel.OrganizationTreeListExcel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：组织架构服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    private final OrganizationRepository organizationRepository;
    @Value("${yitihua.push.appId}")
    Long appId;

    public OrganizationServiceImpl(OrganizationRepository organizationRepository) {
        this.organizationRepository = organizationRepository;
    }


    /**
     * 创建组织架构
     *
     * @param param
     */
    @Override
    public void createOrganization(CreateOrganizationParam param) {
        Organization organization = new Organization();
        BeanUtils.copyProperties(param, organization);
        Long id = IdGenerator.SNOW.generate();
        organization.setId(id);
        organizationRepository.create(organization);
    }

    /**
     * 修改组织架构
     *
     * @param param
     */
    @Override
    public void editOrganization(EditOrganizationParam param) {
        Long id = param.getId();
        Organization organization = organizationRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, organization);
        organizationRepository.edit(organization);
    }

    /**
     * 移除组织架构
     *
     * @param id
     */
    @Override
    public void removeOrganization(Long id) {
        organizationRepository.removeById(id);
    }

    /**
     * 启动/禁用组织架构
     *
     * @param id
     */
    @Override
    public void enabledOrganization(Long id) {
        Organization organization = organizationRepository.getByIdCheck(id);
        organization.setIsDisable(!organization.getIsDisable());
        organizationRepository.edit(organization);
    }

    /**
     * 获取组织架构详情
     *
     * @param id
     * @return
     */
    @Override
    public GetOrganizationVo getOrganization(Long id) {
        Organization organization = organizationRepository.getByIdCheck(id);
        GetOrganizationVo vo = new GetOrganizationVo();
        BeanUtils.copyProperties(organization, vo);
        return vo;
    }

    /**
     * 获取组织架构 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetOrganizationListVo> getOrganizationList(GetOrganizationListParam param) {

        SelectOrganizationDto dto = new SelectOrganizationDto();
        BeanUtils.copyProperties(param, dto);
        Page<Organization> page = organizationRepository.selectOrganization(dto);
        List<Organization> organizationList = page.getRecords();
        List<GetOrganizationListVo> list = new ArrayList<>();
        for (Organization organization : organizationList) {
            GetOrganizationListVo vo = new GetOrganizationListVo();
            BeanUtils.copyProperties(organization, vo);

            list.add(vo);
        }
        return new PageResult<>(list, page);

    }

    /**
     * 获取组织架构下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetOrganizationDownListVo> getOrganizationDownList(GetOrganizationDownListParam param) {
        Organization po = new Organization();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
            po.setIsDelete(false);
            po.setIsDisable(false);
        }
        List<Organization> organizationList = organizationRepository.getListByEntity(po);

        List<GetOrganizationDownListVo> list = new ArrayList<>();
        for (Organization organization : organizationList) {
            GetOrganizationDownListVo vo = new GetOrganizationDownListVo();
            BeanUtils.copyProperties(organization, vo);
            list.add(vo);
        }
        return list;
    }

    /**
     * 获取组织架构树形
     *
     * @return
     */
    @Override
    public List<GetOrganizationTreeListVo> getOrganizationTreeList() {
        Organization po = new Organization();
        po.setIsDelete(false);
        po.setIsDisable(false);
        List<Organization> organizationList = organizationRepository.getListByEntity(po);

        List<GetOrganizationTreeListVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(organizationList)) {
            for (Organization organization : organizationList) {
                GetOrganizationTreeListVo vo = new GetOrganizationTreeListVo();
                BeanUtils.copyProperties(organization, vo);
                voList.add(vo);
            }

            Map<Long, List<GetOrganizationTreeListVo>> departmentMap = voList.stream().collect(Collectors.groupingBy(GetOrganizationTreeListVo::getParentId));
            for (GetOrganizationTreeListVo nodeVo : voList) {
                List<GetOrganizationTreeListVo> vos = departmentMap.get(nodeVo.getId());
                nodeVo.setChildList(vos);
            }

            List<GetOrganizationTreeListVo> vos = voList.stream().filter(r -> {
                return r.getParentId().equals(appId);
            }).collect(Collectors.toList());

            return vos;
        }
        return voList;
    }

    /**
     * 导入组织架构
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public void importOrganization(MultipartFile file) {
        StringBuffer error = new StringBuffer();

        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setStartRows(0);

            List<OrganizationTreeListExcel> result = ExcelImportUtil.importExcel(file.getInputStream(), OrganizationTreeListExcel.class, params);
            for (OrganizationTreeListExcel excel : result) {
                Organization organization = organizationRepository.selectByName(excel.getParentName());
                if (organization == null) {
                    error.append(excel.getName()+"的上级组织架构不存在，上级名称："+excel.getParentName()+"\n");
                    continue;
                }else{
                    Organization organization1 = new Organization();
                    organization1.setId(IdGenerator.SNOW.generate());
                    organization1.setName(excel.getName());
                    organization1.setParentId(organization.getId());
                    //根据传入的type转换成枚举
                    organization1.setType(OrganizationTypeEnum.getEnumByName(excel.getType()));
                    organizationRepository.save(organization1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        if (!StringUtils.isEmpty(error.toString())) {
            throw new BizException(error.toString());
        }

    }


}



